package org.dalmatian.common.satoken.core.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;


/**
 * SaToken异常处理器
 *
 * @author Lion Li
 */
@Slf4j
@Component
public class SaTokenExceptionInterceptor implements RouterInterceptor {


    private final Integer HTTP_FORBIDDEN = 403;
    private final Integer HTTP_UNAUTHORIZED = 401;

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain)
        throws Throwable {
        try {
            chain.doIntercept(ctx, mainHandler);
        } catch (NotPermissionException e) {
            String requestUrl = ctx.path();
            log.error("请求地址'{}',权限码校验失败'{}'", requestUrl, e.getMessage());
            ctx.status(HTTP_FORBIDDEN);
            ctx.render(Result.failure(HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权"));
        } catch (NotRoleException e) {
            String requestUrl = ctx.path();
            log.error("请求地址'{}',角色权限校验失败'{}'", requestUrl, e.getMessage());
            ctx.status(HTTP_UNAUTHORIZED);
            ctx.render(Result.failure(HTTP_UNAUTHORIZED, "没有访问权限，请联系管理员授权"));
        } catch (NotLoginException e) {
            ctx.status(HTTP_UNAUTHORIZED);
            ctx.render(Result.failure(HTTP_UNAUTHORIZED, "认证失败，无法访问系统资源"));
        } catch (SaTokenException e) {

            ctx.status(HTTP_UNAUTHORIZED);
            e.printStackTrace();
            ctx.render(Result.failure(HTTP_UNAUTHORIZED, e.getMessage()));
        }

    }
}
